/******************************************************************************
 * @File name   :      IPackageInventoryService.java
 *
 * @Author      :      JIZHANGS
 *
 * @Date        :      Jul 22, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2015 Capgemini, Inc. All  Rights Reserved.
 * This software is published under the terms of the Capgemini Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * Jul 22, 2015 11:40:05 AM        JIZHANGS     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.remind.service.impl;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.cap.bts.commonfunc.common.constant.SmsTemplateNoConstants;
import com.cap.bts.commonfunc.common.constant.SmsTemplateVariable;
import com.cap.bts.commonfunc.common.dto.SmsContentDetailDto;
import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.commonfunc.sms.dao.IShortMessageTemplateDao;
import com.cap.bts.commonfunc.sms.domain.SmsTemplate;
import com.cap.bts.crmdp.commons.sftp.SFTPProcessor;
import com.cap.bts.crmdp.commons.sftp.SftpProperties;
import com.cap.bts.crmdp.dealer.dealerinfosync.dao.IDealerInfoSyncDao;
import com.cap.bts.crmdp.dealer.dealerinfosync.domain.DealerInfoRelMars;
import com.cap.bts.crmdp.dealer.dealerinfosync.service.IDealerInfoSyncService;
import com.cap.bts.crmdp.dealer.dealerinfosync.util.ProcessCsvFileUtils;
import com.cap.bts.crmdp.dealer.logistic.dao.IMaintainLogisticDao;
import com.cap.bts.crmdp.dealer.logistic.dao.IMaintainLogisticHistoryDao;
import com.cap.bts.crmdp.dealer.logistic.domain.LogisticProcess;
import com.cap.bts.crmdp.dealer.logistic.domain.LogisticProcessHistory;
import com.cap.bts.crmdp.dealer.masterdata.dao.IMaintainDealerDao;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.purchase.constants.PurchaseConstants;
import com.cap.bts.crmdp.dealer.remind.dao.ICustomPromotionDao;
import com.cap.bts.crmdp.dealer.remind.dao.ICustomerDao;
import com.cap.bts.crmdp.dealer.remind.dao.ICustomerGroupDao;
import com.cap.bts.crmdp.dealer.remind.dao.IHQPromotionDao;
import com.cap.bts.crmdp.dealer.remind.dao.IRemindDao;
import com.cap.bts.crmdp.dealer.remind.dao.IRemindQuotaDao;
import com.cap.bts.crmdp.dealer.remind.dao.IServiceRemindArchDao;
import com.cap.bts.crmdp.dealer.remind.dao.IServiceRemindDao;
import com.cap.bts.crmdp.dealer.remind.dao.IServiceRemindHistoryDao;
import com.cap.bts.crmdp.dealer.remind.dao.ITrCustomerGroupDao;
import com.cap.bts.crmdp.dealer.remind.dao.IVehicleDao;
import com.cap.bts.crmdp.dealer.remind.domain.CustomPromotion;
import com.cap.bts.crmdp.dealer.remind.domain.CustomerGroup;
import com.cap.bts.crmdp.dealer.remind.domain.HQPromotion;
import com.cap.bts.crmdp.dealer.remind.domain.RemindQuota;
import com.cap.bts.crmdp.dealer.remind.domain.ServiceRemind;
import com.cap.bts.crmdp.dealer.remind.domain.ServiceRemindHistory;
import com.cap.bts.crmdp.dealer.remind.domain.TrCustomerGroup;
import com.cap.bts.crmdp.dealer.remind.dto.CustomerDto;
import com.cap.bts.crmdp.dealer.remind.dto.CustomerPromotionDto;
import com.cap.bts.crmdp.dealer.remind.dto.MsgPackageDto;
import com.cap.bts.crmdp.dealer.remind.dto.RemindDto;
import com.cap.bts.crmdp.dealer.remind.dto.RemindForSMSDto;
import com.cap.bts.crmdp.dealer.remind.dto.RemindSettingsDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceRemindDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceRemindForMemberDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceRemindHistoryDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceRemindInterimDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceRemindSubmitDto;
import com.cap.bts.crmdp.dealer.remind.dto.ServiceTypeDto;
import com.cap.bts.crmdp.dealer.remind.dto.SftpFileDto;
import com.cap.bts.crmdp.dealer.remind.dto.VehicleDto;
import com.cap.bts.crmdp.dealer.remind.service.IRemindService;
import com.cap.bts.framework.codemapping.dao.ICodeMappingDao;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.sms.service.ISmContentService;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;


/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class RemindServiceImpl implements IRemindService {

    private static final Logger LOGGER = Logger.getLogger(RemindServiceImpl.class);
    
    public static final int IS_POTENTIAL_LOSS=1;
    public static final int IS_NOT_POTENTIAL_LOSS=0;
    @Autowired
    IDealerInfoSyncDao dealerInfoSyncDao;
    @Autowired
    IDealerInfoSyncService dealerInfoSyncService;
    @Autowired
    IMaintainLogisticDao maintainLogisticDao;
    @Autowired
    IRemindDao remindDao;
    
    @Autowired
    IMaintainDealerDao maintainDealerDao;

    @Autowired
    IServiceRemindHistoryDao serviceRemindHistoryDao;
    
    @Autowired
    private IShortMessageTemplateDao msgTemplateDao;
    
    @Autowired
    ISmContentService smContentService;
    
    @Autowired
    IRemindQuotaDao remindQuotaDao;
    @Autowired
    ICodeMappingDao codeMapping;
    
    @Autowired
    IMaintainLogisticHistoryDao maintainLogisticHistoryDao;
    
    @Autowired
    IServiceRemindDao serviceRemindDao;
    
    @Autowired
    IServiceRemindArchDao serviceRemindArchDao;
    
    @Autowired
    ICustomerDao customerDao;
    
    @Autowired
    IVehicleDao vehicleDao;

    @Autowired
    private ICodeMapping codeMappingService;
    
    @Autowired
    private IHQPromotionDao hQPromotionDao;
    
    @Autowired
    private ICustomPromotionDao customPromotionDao;
    
    @Autowired
    private ITrCustomerGroupDao trCustomerGroupDao;
    
    @Autowired
    private ICustomerGroupDao customerGroupDao;
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Nov 25, 2015
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#getRemindListByMemberNameOrMoblieOrCarPlate(com.cap.bts.crmdp.dealer.remind.dto.RemindDto)
     **/
    @Override
    public List<RemindDto> getRemindListByMemberNameOrMoblieOrCarPlate(RemindDto dto)
        throws AppException {
        //每月重置短信初始条数
        CodeInfo codeInfo=codeMapping.getCodeInfoByCode("RemindDefaultQuantity");
        
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(remindQuota!=null){
            remindQuota = remindQuotaDao.findById(remindQuota.getId());
            Date today=new Date();
            Calendar c=Calendar.getInstance();
            c.setTime(today);
            int today_month=c.get(Calendar.MONTH);
            if(remindQuota.getExpireDate()!=null){
                c.setTime(remindQuota.getExpireDate());
            }
            int expire_month=c.get(Calendar.MONTH);
            if(today_month!=expire_month){
                if(codeInfo!=null){
                    remindQuota.setDefaultQuantity(Integer.valueOf(codeInfo.getValue()));
                }else{
                    remindQuota.setDefaultQuantity(0);
                }
                remindQuota.setExpireDate(new Date());
            }
        }else{
            remindQuota=new RemindQuota();
            remindQuota.setDealerId(UserUtil.getCurrentUser().getDealerId());
            remindQuota.setPurchaseQuantity(0);
            if(codeInfo!=null){
                remindQuota.setDefaultQuantity(Integer.valueOf(codeInfo.getValue()));
            }else{
                remindQuota.setDefaultQuantity(0);
            }
            remindQuota.setExpireDate(new Date());
            remindQuotaDao.save(remindQuota);
        }
        //取得显示信息
        List<RemindDto> remindDtoList = remindDao.getRemindListByMemberNameOrMoblieOrCarPlate(dto);
        /*if(remindDtoList != null && !remindDtoList.isEmpty()){
        	for(int i = 0; i < remindDtoList.size(); i++){
        		processServiceRemindForShow(remindDtoList.get(i), UserUtil.getCurrentUser().getDealerId());
        	}
        }*/
        return remindDtoList;
    }

    /**
     * 
     * @Date : Sep 15, 2015
     * @param sendAllFlag
     * @param remindDtos
     * @throws AppException
     */
    public    Map<String, Object> sendAllRemindInfo(boolean resend,boolean appSendFlag, boolean wechatSendFlag, boolean msgSendFlag,
        RemindDto dto) throws AppException {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        rtnMap.put("successMsg", "发送成功！");
        Map<String, String> paraMap = new HashMap<String, String>();
        if(dto==null){
            throw new AppException("sendRemindInfoList", "客户列表为空！");
        }
        String month = dto.getqRemindStartDate();
        if(month != "" || month != null){
        	try {
        		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        		int selectedMonthNum = Integer.parseInt(month.substring(5, 7));
        		String dateNow = format.format(new Date());
        		int dateNowNum = Integer.parseInt(dateNow.substring(5, 7));
        		int num = selectedMonthNum - dateNowNum;
        		
        		int selectedYearNum = Integer.parseInt(month.substring(0,4));
        		int dateNowYearNum = Integer.parseInt(dateNow.substring(0,4));
        		int yearNum = selectedYearNum - dateNowYearNum;
        		
        		Calendar c = Calendar.getInstance();
        		c.add(Calendar.YEAR, yearNum);
        		c.add(Calendar.MONTH, num);
        		//设置为1号,当前日期既为该月第一天
        		c.set(Calendar.DAY_OF_MONTH,1);
        		String dateNowFirst = format.format(c.getTime());
        		//获取该月最后一天
        		Calendar ca = Calendar.getInstance();
        		ca.add(Calendar.YEAR, yearNum);
        		ca.add(Calendar.MONTH, num);
        		ca.set(Calendar.DAY_OF_MONTH,ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        		String dateNowLast = format.format(ca.getTime());
        		dto.setqRemindStartDate(dateNowFirst);
        		dto.setqRemindEndDate(dateNowLast);
        	} catch (Exception e) {
        		LOGGER.error("dateFormatProcessError", e);
        	}
        }
        List<RemindDto> remindDtos = remindDao.getRemindListByMemberNameOrMoblieOrCarPlateNoPage(dto);
        List<RemindDto> tempDtos=new ArrayList<RemindDto>();
        for(RemindDto t: remindDtos){
                tempDtos.add(t); 
        }
        
        if(tempDtos.isEmpty()){
            throw new AppException("sendRemindInfoList", "请选择客户后,发送！");
        }
        
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(remindQuota!=null){
            remindQuota=remindQuotaDao.findById(remindQuota.getId());
        }else{
            throw new AppException("reduceRemindQuantityByDealerId","找不到门店的短信包信息！");
        }
        
        if(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity()<tempDtos.size()){
            throw new AppException("reduceRemindQuantityByDealerId","发送"+tempDtos.size()+"条短信,短信包余额为"+(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity())+"条,余额不足,请去充值！");
        }
      
        
            SmsContentDetailDto smsDto = new SmsContentDetailDto();
            MasterDataDealerInfo dearInfo=maintainDealerDao.getDealerByDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
            Integer sendCount=0;
          //合并短信发送
            List<RemindForSMSDto> mobileAndCarPlateList = new ArrayList<RemindForSMSDto>();
            //取出所有要发的手机号
            for(int i=0; i<tempDtos.size(); i++){
            	String mobilePhone = tempDtos.get(i).getMobliePhone();
            	String carPlate = tempDtos.get(i).getCarPlate();
                RemindForSMSDto remindForSMSDto = new RemindForSMSDto();
            	if(i == 0){
            		remindForSMSDto.setMobliePhone(mobilePhone);
            		remindForSMSDto.setCarPlate(carPlate);
            		mobileAndCarPlateList.add(remindForSMSDto);
            	}else{
            		boolean isExists = false;
            		for(int j=0; j<mobileAndCarPlateList.size(); j++){
            			String mobilePhoneJ = mobileAndCarPlateList.get(j).getMobliePhone();
            			String carPlateJ = mobileAndCarPlateList.get(j).getCarPlate();
            			if(Utils.getString(mobilePhone).equals(Utils.getString(mobilePhoneJ))
            					&& Utils.getString(carPlate).equals(Utils.getString(carPlateJ))){
            				isExists = true;
            			}
            		}
            		if(!isExists){
            			remindForSMSDto.setMobliePhone(mobilePhone);
                		remindForSMSDto.setCarPlate(carPlate);
                		mobileAndCarPlateList.add(remindForSMSDto);
            		}
            	}
            }
            //根据手机号将要发的信息进行整合
            List<RemindDto> preRemindDtos = new ArrayList<RemindDto>();
            if(mobileAndCarPlateList != null && !mobileAndCarPlateList.isEmpty()){
            	for(RemindForSMSDto remindForSMSDto:mobileAndCarPlateList){
            		RemindDto remindDtoForInsert = new RemindDto();
            		String carplateString = "";
            		String maintenanceItem = "";
            		String lastPartBrand = "";
            		for(int i=0; i<tempDtos.size(); i++){
            			RemindDto remindDto = tempDtos.get(i);
            			if(remindForSMSDto.getMobliePhone().equals(remindDto.getMobliePhone())
            					&& remindForSMSDto.getCarPlate().equals(remindDto.getCarPlate())){
            				String memberName = remindDto.getMemberName();
            				
            				if(!(carplateString.equals(remindDto.getCarPlate() + " "))){
            					carplateString += remindDto.getCarPlate() + " ";
            				}
            				
            				String nextCalcDate = remindDto.getNextCalcDate().substring(0, 7);
            				
            				if(!(maintenanceItem.equals(remindDto.getMaintenanceItem() + " "))){
            					maintenanceItem += remindDto.getMaintenanceItem() + " ";
            				}
            				
            				if(!(lastPartBrand.equals(remindDto.getLastPartBrand() + " "))){
            					lastPartBrand += remindDto.getLastPartBrand() + " ";
            				}
            				
            				remindDtoForInsert.setMemberName(memberName);
            				remindDtoForInsert.setMobliePhone(remindForSMSDto.getMobliePhone());
            				remindDtoForInsert.setCarPlate(carplateString);
            				remindDtoForInsert.setNextCalcDate(nextCalcDate);
            				remindDtoForInsert.setMaintenanceItem(maintenanceItem);
            				remindDtoForInsert.setLastPartBrand(lastPartBrand);
            			}
            		}
            		preRemindDtos.add(remindDtoForInsert);
            	}
            }
            //对处理好的列表发短信
            if(!preRemindDtos.isEmpty()){
            	for(RemindDto remindDto : preRemindDtos){
                    paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
                    paraMap.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
                    paraMap.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
                    paraMap.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate());
                    paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
                    paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
                    if(dearInfo!=null){
                        paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                        paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                    }
                    smsDto.setTemplateNo(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
                   try{
                       smsDto.setDestMobile(Long.valueOf(remindDto.getMobliePhone()));
                   }catch(Exception e){
                       rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                       continue;
                   }
                    smsDto.setParaMap(paraMap);
                    try{
                        smContentService.createSmsContent(smsDto);
                    }catch(Exception e){
                       /* rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                        continue;*/
                    }
            	}
            }
            //处理history
            for (RemindDto remindDto : tempDtos) {
            	Map<String, String> paraMapForHistory = new HashMap<String, String>();
            	paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate().substring(0, 10));
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
                if(dearInfo!=null){
                    paraMapForHistory.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                    paraMapForHistory.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                }
                sendCount++;
                ServiceRemindHistory srh=new ServiceRemindHistory();
                srh.setDealerId(UserUtil.getCurrentUser().getDealerId());
                List<SmsTemplate> smsTemplates = msgTemplateDao.findTemplateByTemplateCode(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
                String msgContent="";
                if(smsTemplates!=null){
                    msgContent=smContentService.generateSmsContent(smsTemplates.get(0),paraMapForHistory);
                }
                srh.setServiceRemindId(remindDto.getId());
                srh.setMessageContent(msgContent);
                srh.setStatus(1);
                serviceRemindHistoryDao.save(srh);
            }
           /* for (RemindDto remindDto : tempDtos) {
                paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
                paraMap.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
                paraMap.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
                paraMap.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate().substring(0, 10));
                paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
                paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
                if(dearInfo!=null){
                    paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                    paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getContactPhone());
                }
                smsDto.setTemplateNo(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
                try{
                    smsDto.setDestMobile(Long.valueOf(remindDto.getMobliePhone()));
                }catch(Exception e){
                    rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                    continue;
                }
                smsDto.setParaMap(paraMap);
                try{
                    smContentService.createSmsContent(smsDto);
                }catch(Exception e){
                    rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                    continue;
                }
                sendCount++;
                ServiceRemindHistory srh=new ServiceRemindHistory();
                srh.setDealerId(UserUtil.getCurrentUser().getDealerId());
                List<SmsTemplate> smsTemplates = msgTemplateDao.findTemplateByTemplateCode(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
                String msgContent="";
                if(smsTemplates!=null){
                    msgContent=smContentService.generateSmsContent(smsTemplates.get(0),paraMap);
                }
                srh.setServiceRemindId(remindDto.getId());
                srh.setMessageContent(msgContent);
                srh.setStatus(1);
                serviceRemindHistoryDao.save(srh);
            }*/
            try{
                reduceRemindQuantityByDealerId(UserUtil.getCurrentUser().getDealerId(),sendCount);
            }catch(AppException e){
                LOGGER.error("门店："+UserUtil.getCurrentUser().getDealerId()+"发送短信减少短信数量出错,实际发送短信数量为"+sendCount, e);
                throw new AppException("sendAllRemindInfo", "发送成功,减少短信数量失败,请联系系统管理员！");
            }
            
            return rtnMap;
       
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Sep 15, 2015
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#sendRemindInfoList(boolean,
     *      boolean, boolean, java.util.List)
     **/
    @Override
    public Map<String, Object> sendRemindInfoList(boolean resend,boolean appSendFlag, boolean wechatSendFlag,
        boolean msgSendFlag, List<RemindDto> dto) throws AppException {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        rtnMap.put("successMsg", "发送成功！");
        Map<String, String> paraMap = new HashMap<String, String>();
        List<RemindDto> tempDtos=new ArrayList<RemindDto>();
        if(dto==null){
            throw new AppException("sendRemindInfoList", "客户列表为空！");
        }
        for(RemindDto t: dto){
            if(t.getCheckFlag()!=null){
                tempDtos.add(t); 
            }
        }
        
        if(tempDtos.isEmpty()){
            throw new AppException("sendRemindInfoList", "请选择客户后,发送！");
        }
        
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(remindQuota!=null){
            remindQuota=remindQuotaDao.findById(remindQuota.getId());
        }else{
            throw new AppException("reduceRemindQuantityByDealerId","找不到门店的短信包信息！");
        }
        
        if(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity()<tempDtos.size()){
            throw new AppException("reduceRemindQuantityByDealerId","发送"+tempDtos.size()+"条短信,短信包余额为"+(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity())+"条,余额不足,请去充值！");
        }
      
        SmsContentDetailDto smsDto = new SmsContentDetailDto();
        MasterDataDealerInfo dearInfo=maintainDealerDao.getDealerByDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
        Integer sendCount=0;
        //合并短信发送
        List<RemindForSMSDto> mobileAndCarPlateList = new ArrayList<RemindForSMSDto>();
        //取出所有要发的手机号
        for(int i=0; i<tempDtos.size(); i++){
        	String mobilePhone = tempDtos.get(i).getMobliePhone();
        	String carPlate = tempDtos.get(i).getCarPlate();
            RemindForSMSDto remindForSMSDto = new RemindForSMSDto();
        	if(i == 0){
        		remindForSMSDto.setMobliePhone(mobilePhone);
        		remindForSMSDto.setCarPlate(carPlate);
        		mobileAndCarPlateList.add(remindForSMSDto);
        	}else{
        		boolean isExists = false;
        		for(int j=0; j<mobileAndCarPlateList.size(); j++){
        			String mobilePhoneJ = mobileAndCarPlateList.get(j).getMobliePhone();
        			String carPlateJ = mobileAndCarPlateList.get(j).getCarPlate();
        			if(Utils.getString(mobilePhone).equals(Utils.getString(mobilePhoneJ))
        					&& Utils.getString(carPlate).equals(Utils.getString(carPlateJ))){
        				isExists = true;
        			}
        		}
        		if(!isExists){
        			remindForSMSDto.setMobliePhone(mobilePhone);
            		remindForSMSDto.setCarPlate(carPlate);
            		mobileAndCarPlateList.add(remindForSMSDto);
        		}
        	}
        }
        //根据手机号将要发的信息进行整合
        List<RemindDto> preRemindDtos = new ArrayList<RemindDto>();
        if(mobileAndCarPlateList != null && !mobileAndCarPlateList.isEmpty()){
        	for(RemindForSMSDto remindForSMSDto:mobileAndCarPlateList){
        		RemindDto remindDtoForInsert = new RemindDto();
        		String carplateString = "";
        		String maintenanceItem = "";
        		String lastPartBrand = "";
        		for(int i=0; i<tempDtos.size(); i++){
        			RemindDto remindDto = tempDtos.get(i);
        			if(remindForSMSDto.getMobliePhone().equals(remindDto.getMobliePhone())
        					&& remindForSMSDto.getCarPlate().equals(remindDto.getCarPlate())){
        				String memberName = remindDto.getMemberName();
        				
        				if(!(carplateString.equals(remindDto.getCarPlate() + " "))){
        					carplateString += remindDto.getCarPlate() + " ";
        				}
        				
        				String nextCalcDate = remindDto.getNextCalcDate().substring(0, 7);
        				
        				if(!(maintenanceItem.equals(remindDto.getMaintenanceItem() + " "))){
        					maintenanceItem += remindDto.getMaintenanceItem() + " ";
        				}
        				
        				if(!(lastPartBrand.equals(remindDto.getLastPartBrand() + " "))){
        					lastPartBrand += remindDto.getLastPartBrand() + " ";
        				}
        				
        				remindDtoForInsert.setMemberName(memberName);
        				remindDtoForInsert.setMobliePhone(remindForSMSDto.getMobliePhone());
        				remindDtoForInsert.setCarPlate(carplateString);
        				remindDtoForInsert.setNextCalcDate(nextCalcDate);
        				remindDtoForInsert.setMaintenanceItem(maintenanceItem);
        				remindDtoForInsert.setLastPartBrand(lastPartBrand);
        			}
        		}
        		preRemindDtos.add(remindDtoForInsert);
        	}
        }
        //对处理好的列表发短信
        if(!preRemindDtos.isEmpty()){
        	for(RemindDto remindDto : preRemindDtos){
                paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
                paraMap.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
                paraMap.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
                paraMap.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate());
                paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
                paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
                if(dearInfo!=null){
                    paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                    paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                }
                smsDto.setTemplateNo(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
               try{
                   smsDto.setDestMobile(Long.valueOf(remindDto.getMobliePhone()));
               }catch(Exception e){
                   rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                   continue;
               }
                smsDto.setParaMap(paraMap);
                try{
                    smContentService.createSmsContent(smsDto);
                }catch(Exception e){
                   /* rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                    continue;*/
                }
        	}
        }
        //处理history
        for (RemindDto remindDto : tempDtos) {
        	Map<String, String> paraMapForHistory = new HashMap<String, String>();
        	paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate().substring(0, 10));
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
            if(dearInfo!=null){
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
            }
            sendCount++;
            ServiceRemindHistory srh=new ServiceRemindHistory();
            srh.setDealerId(UserUtil.getCurrentUser().getDealerId());
            List<SmsTemplate> smsTemplates = msgTemplateDao.findTemplateByTemplateCode(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
            String msgContent="";
            if(smsTemplates!=null){
                msgContent=smContentService.generateSmsContent(smsTemplates.get(0),paraMapForHistory);
            }
            srh.setServiceRemindId(remindDto.getId());
            srh.setMessageContent(msgContent);
            srh.setStatus(1);
            serviceRemindHistoryDao.save(srh);
        }
        /*for (RemindDto remindDto : tempDtos) {
            paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
            paraMap.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
            paraMap.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
            paraMap.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate().substring(0, 10));
            paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
            paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
            if(dearInfo!=null){
                paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
            }
            smsDto.setTemplateNo(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
           try{
               smsDto.setDestMobile(Long.valueOf(remindDto.getMobliePhone()));
           }catch(Exception e){
               rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
               continue;
           }
            smsDto.setParaMap(paraMap);
            try{
                smContentService.createSmsContent(smsDto);
            }catch(Exception e){
                rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                continue;
            }
            sendCount++;
            ServiceRemindHistory srh=new ServiceRemindHistory();
            srh.setDealerId(UserUtil.getCurrentUser().getDealerId());
            List<SmsTemplate> smsTemplates = msgTemplateDao.findTemplateByTemplateCode(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
            String msgContent="";
            if(smsTemplates!=null){
                msgContent=smContentService.generateSmsContent(smsTemplates.get(0),paraMap);
            }
            srh.setServiceRemindId(remindDto.getId());
            srh.setMessageContent(msgContent);
            srh.setStatus(1);
            serviceRemindHistoryDao.save(srh);
        }*/
        try{
            reduceRemindQuantityByDealerId(UserUtil.getCurrentUser().getDealerId(),sendCount);
        }catch(AppException e){
            LOGGER.error("门店："+UserUtil.getCurrentUser().getDealerId()+"发送短信减少短信数量出错,实际发送短信数量为"+sendCount, e);
            throw new AppException("sendAllRemindInfo", "发送成功,减少短信数量失败,请联系系统管理员！");
        }
        return rtnMap;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Dec 2, 2015
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#getRemindHistoryList(com.cap.bts.crmdp.dealer.remind.dto.RemindDto)
    **/
    @Override
    public List<RemindDto> getRemindHistoryList(RemindDto dto) throws AppException {
        
        return remindDao.getRemindHistoryList(dto);
        
    }
    
    
    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Dec 2, 2015
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#getRemindHistoryList(com.cap.bts.crmdp.dealer.remind.dto.RemindDto)
    **/
    @Override
    public List<RemindDto> getRemindHistoryListByUserAndServiceType(RemindDto dto) throws AppException {
        
        return remindDao.getRemindHistoryListByUserAndServiceType(dto);
    }



    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Dec 2, 2015
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#getRemindQuotaByDealerId(java.lang.Long)
    **/
    @Override
    public RemindQuota getRemindQuotaByDealerId(Long dealerId) throws AppException {
        return remindQuotaDao.getRemindQuotaByDealerId(dealerId);
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Feb 2, 2016
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#reduceRemindQuantityByDealerId(java.lang.Long, java.lang.Integer)
    **/
    @Override
    public void reduceRemindQuantityByDealerId(Long dealerId, Integer quantity) throws AppException {
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(dealerId);
        if(remindQuota!=null){
            remindQuota=remindQuotaDao.findById(remindQuota.getId());
        }else{
            throw new AppException("reduceRemindQuantityByDealerId","找不到门店的短信包信息！");
        }
        
        if(remindQuota.getDefaultQuantity()>=quantity){
            remindQuota.setDefaultQuantity(remindQuota.getDefaultQuantity()-quantity);
        }else if(remindQuota.getDefaultQuantity()<quantity&&remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity()>=quantity){
            remindQuota.setDefaultQuantity(0);
            remindQuota.setPurchaseQuantity(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity()-quantity);
        }else{
            throw new AppException("reduceRemindQuantityByDealerId","发送"+quantity+"条短信,短信包余额为"+(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity())+"条,余额不足,请去充值！");
        }
    }
    
   

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Dec 3, 2015
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#getLogisticProcessListByDealerIdAndLogisticType(java.lang.Long, java.lang.Integer)
    **/
    @Override
    public List<MsgPackageDto> getLogisticProcessListByDealerIdAndLogisticType(Long dealerId
        ) throws AppException {
        List<MsgPackageDto> list=new ArrayList<MsgPackageDto>();
        List<LogisticProcess> logisticList=maintainLogisticDao.getLogisticProcessListByDealerIdAndLogisticType(dealerId,1);
        if(logisticList!=null&&!logisticList.isEmpty()){
            for(LogisticProcess logisticProcess:logisticList){
                MsgPackageDto msgPackageDto=new MsgPackageDto();
                msgPackageDto.setLogisticProcessId(logisticProcess.getId());
                CodeInfo codeInfo=codeMapping.findById(logisticProcess.getCardDefId());
                msgPackageDto.setMsgPackageName(codeInfo.getValue());
                msgPackageDto.setQuantity(logisticProcess.getShippedQuantity());
                msgPackageDto.setSumQuantity(logisticProcess.getShippedQuantity()*Integer.valueOf(codeInfo.getCode()));
                list.add(msgPackageDto);
            }
        }
        return list;
    }
    
    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Dec 3, 2015
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#getLogisticProcessListByDealerIdAndLogisticType(java.lang.Long, java.lang.Integer)
    **/
    @Override
    public  Map<String,Object> updateLogisticProcessList(RemindDto dto,Long dealerId)
         throws AppException {
        Map<String,Object> rtnMap=new HashMap<String, Object>();
        List<MsgPackageDto> tempMsgPackageDtos =dto.getMsgPackageDtos();
        List<MsgPackageDto> msgPackageDtos =new ArrayList<MsgPackageDto>();
        if(tempMsgPackageDtos!=null&&!tempMsgPackageDtos.isEmpty()){
            for(MsgPackageDto msgPackageDto:tempMsgPackageDtos){
                if(msgPackageDto.getReceiveQuantity()!=null){
                    msgPackageDtos.add(msgPackageDto);
                }
            }
        }
        if(msgPackageDtos.isEmpty()){
            throw new AppException("updateLogisticProcessList", "请选择短信包！");
        }
        
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(dealerId);
        if(remindQuota!=null){
            remindQuota=remindQuotaDao.findById(remindQuota.getId());
        }else{
            throw new AppException("reduceRemindQuantityByDealerId","找不到门店的短信包信息！");
        }
        
        Integer sumQuantity=0;
        for(MsgPackageDto msgPackageDto:msgPackageDtos){
            LogisticProcess logisticProcess =  maintainLogisticDao.findById(msgPackageDto.getLogisticProcessId());
            if(logisticProcess!=null){
                logisticProcess.setReceiveDate(new Date());
                logisticProcess.setReceivedQuantity(msgPackageDto.getReceiveQuantity());
                logisticProcess.setShippedQuantity(logisticProcess.getShippedQuantity()-msgPackageDto.getReceiveQuantity());
                logisticProcess.setStatus(1);
                CodeInfo codeInfo=codeMapping.findById(logisticProcess.getCardDefId());
                sumQuantity+=Integer.valueOf(codeInfo.getCode())*msgPackageDto.getReceiveQuantity();
                LogisticProcessHistory history=new LogisticProcessHistory();
                history.setLogisticId(logisticProcess.getId());
                history.setReceiveDate(new Date());
                history.setReceivedQuantity(msgPackageDto.getReceiveQuantity());
                maintainLogisticHistoryDao.save(history);
            }else{
                throw new AppException("updateLogisticProcessList", "未找到短信包物流信息！");
            }
        }
        remindQuota.setPurchaseQuantity(remindQuota.getPurchaseQuantity()+sumQuantity);
        rtnMap.put("sumQuantity", sumQuantity);
        return  rtnMap;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Dec 4, 2015
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#getLogisticProcessHistoryListByDealerIdAndLogisticType(java.lang.Long)
    **/
    @Override
    public List<MsgPackageDto> getLogisticProcessHistoryListByDealerIdAndLogisticType(Long dealerId)
        throws AppException {
        List<MsgPackageDto> list=new ArrayList<MsgPackageDto>();
        List<Object[]> logisticList=maintainLogisticDao.getLogisticProcessHistoryListByDealerIdAndLogisticType(dealerId,1);
        if(logisticList!=null&&!logisticList.isEmpty()){
            for(Object[] logisticProcess:logisticList){
                MsgPackageDto msgPackageDto=new MsgPackageDto();
                CodeInfo codeInfo=codeMapping.findById(Long.valueOf(logisticProcess[1].toString()));
                msgPackageDto.setLogisticProcessId(Long.valueOf(logisticProcess[2].toString()));
                msgPackageDto.setMsgPackageName(codeInfo.getValue());
                msgPackageDto.setQuantity(Integer.valueOf(logisticProcess[3].toString()));
                msgPackageDto.setSumQuantity(Integer.valueOf(logisticProcess[3].toString())*Integer.valueOf(codeInfo.getCode()));
                try {
                    msgPackageDto.setReceiveDate(new SimpleDateFormat("yyyy-MM-dd").parse(logisticProcess[4].toString()));
                } catch (ParseException e) {
                    throw new AppException("getLogisticProcessHistoryListByDealerIdAndLogisticType", "日期格式错误！");
                }
                list.add(msgPackageDto);
            }
        }
        return list;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Dec 9, 2015
     * @see com.cap.bts.crmdp.dealer.remind.service.IRemindService#saveRemindSetting(com.cap.bts.crmdp.dealer.remind.dto.RemindDto, java.lang.Long)
    **/
    @Override
    public Map<String, Object> saveRemindSetting(RemindSettingsDto dto) throws AppException {
        List<CodeInfo> codeInfos=dto.getCodeInfos();
        for(CodeInfo codeInfo:codeInfos){
            CodeInfo codeInfosave=codeMapping.findById(codeInfo.getId()); 
            codeInfosave.setValue(codeInfo.getValue());
        }
        List<ServiceTypeDto> serviceTypeDtos=dto.getServiceTypeDto();
        for(ServiceTypeDto serviceTypeDto:serviceTypeDtos){
            CodeInfo codeInfosave=codeMapping.findById(serviceTypeDto.getId()); 
            if(!serviceTypeDto.getServiceFlag()){
                codeInfosave.setIsDeleted(1);
            }else{
                codeInfosave.setIsDeleted(0);
            }
        }
        return null;
    }

	@Override
	public List<RemindDto> getRemindListByCarPlate(RemindDto remindDto) throws AppException {
		return remindDao.getRemindListByCarPlate(remindDto);
	}

	@Override
	public void importServiceRemindDataFromFile(File file,String zipName) throws AppException {
		//获取tm_raw_service_remind的数据
		List<ServiceRemindDto> list = ProcessCsvFileUtils.combinationServiceRemindList(ProcessCsvFileUtils.analyzeCsv(file,"UTF-8"));
		List<ServiceRemindInterimDto> interimList = new ArrayList<ServiceRemindInterimDto>();
		if(list != null && !list.isEmpty()){
			for(int i = 0; i < list.size(); i++){
				ServiceRemindInterimDto interim = new ServiceRemindInterimDto();
				ServiceRemindDto serviceRemind = list.get(i);
				interim.setBatchId(zipName);
				interim.setCarModel(serviceRemind.getCarModel());
				interim.setCarPlate(serviceRemind.getCarPlate().replace(" ", ""));
				interim.setDataRequirement(serviceRemind.getCarPlate() + "_" + serviceRemind.getMaintenanceItem());
				if(StringUtils.isNotBlank(serviceRemind.getLastCarcheckMileage())){
					interim.setLastCarcheckMileage(Double.valueOf(serviceRemind.getLastCarcheckMileage()));
				}else{
					interim.setLastCarcheckMileage(null);
				}
				interim.setLastCarcheckStore(serviceRemind.getLastCarcheckStore());
				if(StringUtils.isNotBlank(serviceRemind.getLastMaintenanceMileage())){
					interim.setLastMaintenanceMileage(Double.valueOf(serviceRemind.getLastMaintenanceMileage()));
				}else{
					interim.setLastMaintenanceMileage(null);
				}
				interim.setLastMaintenanceStore(serviceRemind.getLastMaintenanceStore());
				interim.setLastPartBrand(serviceRemind.getLastPartBrand());
				interim.setLastPartName(serviceRemind.getLastPartName());
				interim.setMaintenanceItem(serviceRemind.getMaintenanceItem());
				interim.setMaintenanceSpecBasis(serviceRemind.getMaintenanceSpecBasis());
				interim.setNextCalcbasis(serviceRemind.getNextCalcbasis());
				interim.setUseStandardAverageKM(serviceRemind.getUseStandardAverageKM());
				if(StringUtils.isNotBlank(serviceRemind.getNextCalcMileage())){
					interim.setNextCalcMileage(Double.valueOf(serviceRemind.getNextCalcMileage()));
				}else{
					interim.setNextCalcMileage(null);
				}
				try {
					if(serviceRemind.getLastCalcDate() != null && !"".equals(serviceRemind.getLastCalcDate())){
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						Date data = format.parse(serviceRemind.getLastCalcDate());
						interim.setLastCalcDate(data);
					}else{
						interim.setLastCalcDate(null);
					}
					if(serviceRemind.getLastCarcheckDate() != null && !"".equals(serviceRemind.getLastCarcheckDate())){
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						Date data = format.parse(serviceRemind.getLastCarcheckDate());
						interim.setLastCarcheckDate(data);
					}else{
						interim.setLastCarcheckDate(null);
					}
					if(serviceRemind.getLastMaintenanceDate() != null && !"".equals(serviceRemind.getLastMaintenanceDate())){
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						Date data = format.parse(serviceRemind.getLastMaintenanceDate());
						interim.setLastMaintenanceDate(data);
					}else{
						interim.setLastMaintenanceDate(null);
					}
					if(serviceRemind.getNextCalcDate() != null && !"".equals(serviceRemind.getNextCalcDate())){
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						Date data = format.parse(serviceRemind.getNextCalcDate());
						interim.setNextCalcDate(data);
					}else{
						interim.setNextCalcDate(null);
					}
				} catch (ParseException e) {
					LOGGER.info("error in save serviceRemind",e);
				}
				interimList.add(interim);
			}
			//全部存入临时表
//			serviceRemindDao.deleteServiceRemindInterim();
			serviceRemindDao.insertAllServiceRemind(interimList);
		}
		LOGGER.info("文件名：" + file.getName() + "存表时间：" + new Date() + "内容数量：" + list.size());
	}
	
	@Override
	public void processServiceRemindWithBrakeList(List<ServiceRemind> sRWithBrakeList,String code)throws AppException {
		if(sRWithBrakeList != null && !sRWithBrakeList.isEmpty()){
			//全部删除
			for (int k = 0; k < sRWithBrakeList.size(); k++) {
				serviceRemindDao.remove(sRWithBrakeList.get(k).getId());
			}
			ServiceRemind srWithBrake = null;
			for (int k = 0; k < sRWithBrakeList.size(); k++) {
				//比较时间，与今天距离较近的留下，其他的删除
				for (int k2 = 0; k2 < sRWithBrakeList.size(); k2++) {
					ServiceRemind kSr = sRWithBrakeList.get(k);
					Date kDate = kSr.getNextCalcDate();
					ServiceRemind sr = sRWithBrakeList.get(k2);
					Date date = sr.getNextCalcDate();
					//距离今天的时间差绝对值，取较小的一个
					Long kdays = Math.abs(kDate.getTime() - new Date().getTime());
					Long days = Math.abs(date.getTime() - new Date().getTime());
					//数据删除
					if(kdays > days){
//						serviceRemindDao.remove(sRWithBrakeList.get(k).getId());
						srWithBrake = sr;
					}else{
//						serviceRemindDao.remove(sRWithBrakeList.get(k2).getId());
						srWithBrake = kSr;
					}
				}
				
			}
			//更新剩余的那个最新数据
			if(srWithBrake != null){
				srWithBrake.setMaintenanceItem(code);
				srWithBrake.setId(null);
				serviceRemindDao.save(srWithBrake);
			}
			
		}
	}

	@Override
	public List<ServiceRemind> getServiceRemindByCarPlateAndMaintenance(String carPlate, String maintenance)
			throws AppException {
		return serviceRemindDao.getServiceRemindByCarPlateAndMaintenance(carPlate, maintenance);
	}

	@Override
	public ServiceRemind processServiceRemind(ServiceRemindDto serviceRemindDto) throws AppException {
		if(serviceRemindDto != null){
			ServiceRemind remind = new ServiceRemind();
			remind.setCarModel(serviceRemindDto.getCarModel());
			remind.setCarPlate(serviceRemindDto.getCarPlate());
			try {
				if(StringUtils.isNotBlank(serviceRemindDto.getLastCalcDate())){
					DateFormat creationDate = new SimpleDateFormat("yyyy-MM-dd");
					remind.setLastCalcDate(creationDate.parse(serviceRemindDto.getLastCalcDate()));
				}else{
					remind.setLastCalcDate(null);
				}
				if(StringUtils.isNotBlank(serviceRemindDto.getLastCarcheckDate())){
					DateFormat creationDate = new SimpleDateFormat("yyyy-MM-dd");
					remind.setLastCarcheckDate(creationDate.parse(serviceRemindDto.getLastCarcheckDate()));
				}
				if(StringUtils.isNotBlank(serviceRemindDto.getLastMaintenanceDate())){
					DateFormat creationDate = new SimpleDateFormat("yyyy-MM-dd");
					remind.setLastMaintenanceDate(creationDate.parse(serviceRemindDto.getLastMaintenanceDate()));
				}
				if(StringUtils.isNotBlank(serviceRemindDto.getNextCalcDate())){
					DateFormat creationDate = new SimpleDateFormat("yyyy-MM-dd");
					remind.setNextCalcDate(creationDate.parse(serviceRemindDto.getNextCalcDate()));
				}
			} catch (ParseException e) {
				LOGGER.error("importServiceRemindDataFromFileError", e);
			}
			remind.setLastCarcheckMileage(Double.valueOf(serviceRemindDto.getLastCarcheckMileage()));
			remind.setLastCarcheckStore(serviceRemindDto.getLastCarcheckStore());
			remind.setLastMaintenanceMileage(Double.valueOf(serviceRemindDto.getLastMaintenanceMileage()));
			remind.setLastMaintenanceStore(serviceRemindDto.getLastMaintenanceStore());
			remind.setLastPartBrand(serviceRemindDto.getLastPartBrand());
			remind.setLastPartName(serviceRemindDto.getLastPartName());
			remind.setMaintenanceItem(serviceRemindDto.getMaintenanceItem());
			remind.setMaintenanceSpecBasis(serviceRemindDto.getMaintenanceSpecBasis());
			remind.setNextCalcbasis(serviceRemindDto.getNextCalcbasis());
			remind.setNextCalcMileage(Double.valueOf(serviceRemindDto.getNextCalcMileage()));
			return remind;
		}
		return null;
	}

	@Override
	public void processServiceRemindForShow(RemindDto remindDto,Long dealerNum) throws AppException {
		//判断是否到店
		if(StringUtils.isNotBlank(remindDto.getLastCalcDate()) && !"null".equals(remindDto.getLastCalcDate()) && dealerNum != null){
			if(StringUtils.isNotBlank(remindDto.getLastMaintenanceStore())){
				//上次保养门店是否是当前门店
				if(remindDto.getLastMaintenanceStore().equals(dealerNum.toString())){
					try {
						if(StringUtils.isNotBlank(remindDto.getLastMaintenanceDate()) && !"null".equals(remindDto.getLastMaintenanceDate())){
							DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Long lastMaintenanceDate = dateFormat.parse(remindDto.getLastMaintenanceDate()).getTime();
							Long lastCalcDate = dateFormat.parse(remindDto.getLastCalcDate()).getTime();
							if(lastMaintenanceDate < lastCalcDate){
								remindDto.setIsPotentialLoss(IS_POTENTIAL_LOSS);
							}else{
								remindDto.setIsPotentialLoss(IS_NOT_POTENTIAL_LOSS);
							}
						}else{
							remindDto.setIsPotentialLoss(IS_POTENTIAL_LOSS);
						}
					} catch (ParseException e) {
						LOGGER.error("processServiceRemindOfMaintenanceForShowError",e);
					}
				}else{
					remindDto.setIsPotentialLoss(IS_POTENTIAL_LOSS);
				}
			}else{
				if(StringUtils.isNotBlank(remindDto.getLastCarcheckStore())){
					//上次车检的门店是不是当前门店
					if(remindDto.getLastCarcheckStore().equals(dealerNum.toString()) && !"null".equals(remindDto.getLastCarcheckDate())){
						try {
							if(StringUtils.isNotBlank(remindDto.getLastCarcheckDate())){
								DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
								Long lastCarCheckDate = dateFormat.parse(remindDto.getLastCarcheckDate()).getTime();
								Long lastCalcDate = dateFormat.parse(remindDto.getLastCalcDate()).getTime();
								if(lastCarCheckDate < lastCalcDate){
									remindDto.setIsPotentialLoss(IS_POTENTIAL_LOSS);
								}else{
									remindDto.setIsPotentialLoss(IS_NOT_POTENTIAL_LOSS);
								}
							}else{
								remindDto.setIsPotentialLoss(IS_POTENTIAL_LOSS);
							}
						} catch (ParseException e) {
							LOGGER.error("processServiceRemindOfCarCheckForShowError",e);
						}
					}else{
						remindDto.setIsPotentialLoss(IS_POTENTIAL_LOSS);
					}
				}else{
					remindDto.setIsPotentialLoss(IS_POTENTIAL_LOSS);
				}
			}
		}else{
			remindDto.setIsPotentialLoss(IS_POTENTIAL_LOSS);
		}
	}

	/*@Override
	public void processServiceRemindFileSynchronization() throws AppException {
		try {
			//从SFTP上下载文件
			String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.SERVICE_REMIND_FILE_SYNCHRONIZATION);
			try {
				if(sftpInfo != null){
					SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
					//取出所有的文件
					String prefix = codeMappingService.getCodeValueByCode("SRFromWeCareOP", "SRFromWeCareOP");
					List<SftpFileDto> fileList = getAllFileOrderByDateAsc(sftpProperties, "SRFromWeCareOP");
					SFTPProcessor ftpUtil = new SFTPProcessor();
					ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
					
					if(channelSftp.isConnected()){
						//获取临时目录
						String tmpPath = codeMappingService.getCodeValueByCode("tmpPath", "tmpPath");
						
						for(int j=0; j<fileList.size(); j++){
							try{
								SftpFileDto sftpFileDto = fileList.get(j);
//								String localFile = tmpPath + "ServiceReminderWeCaretoDataHub20160106.zip";
								String localFilePath = tmpPath + "ServiceReminder/ServiceReminder_" + DateFormatUtils.format(new Date(), "yyyyMMdd_HHmmssSSS");
								String localFile = localFilePath + "/" + sftpFileDto.getFileName();
								File file = new File(localFilePath);
								if(!file.exists()){
									file.mkdirs();
								}
								ftpUtil.downloadFile(sftpFileDto.getFileName(), sftpProperties.getPath(), localFile);
								//解压缩
								ProcessCsvFileUtils.unZip(localFile, localFilePath);
								String localUnZipFile = localFilePath + "/MaintenanceStatus.csv";
								importServiceRemindDataFromFile(new File(localUnZipFile),sftpFileDto.getFileName());
								
								//将处理过的压缩包删除
								ftpUtil.remove(sftpProperties.getPath() + sftpFileDto.getFileName());		
								}catch(Exception e){
									LOGGER.error("processServiceRemindFileError",e);
								}
						}
						
					}
					ftpUtil.closeChannel();
				}
			} catch (RuntimeException e) {
				LOGGER.info("downLodeServiceRemindFile", e);
			} catch (Exception e) {
				LOGGER.info("downLodeServiceRemindFile", e);
			}
		} catch (AppException e) {
			throw new AppException("Exception processServiceRemindFileSynchronization", e);
		}
	}*/

	/*@Override
	public void processCustomerVehicleFile() throws AppException {
		//从SFTP上下载文件
		String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.SERVICE_REMIND_FILE_SYNCHRONIZATION);
		try {
			if(sftpInfo != null){
				SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
				//取出所有的文件
				String prefix = codeMappingService.getCodeValueByCode("SRFromMARS", "SRFromMARS");
				List<SftpFileDto> fileList = getAllFileOrderByDateAsc(sftpProperties, "SRFromMARS");
				
				SFTPProcessor ftpUtil = new SFTPProcessor();
				ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
				
				if(channelSftp.isConnected()){
					//获取临时目录
					String tmpPath = codeMappingService.getCodeValueByCode("tmpPath", "tmpPath");
					
					for(int j=0; j<fileList.size(); j++){
						try{
							SftpFileDto sftpFileDto = fileList.get(j);
							String localFilePath = tmpPath + "ServiceReminder/CustomerAndVehicle_" + DateFormatUtils.format(new Date(), "yyyyMMdd_HHmmssSSS");
							String localFile = localFilePath + "/" + sftpFileDto.getFileName();
							File file = new File(localFilePath);
							if(!file.exists()){
								file.mkdirs();
							}
							ftpUtil.downloadFile(sftpFileDto.getFileName(), sftpProperties.getPath(), localFile);
							//解压缩
							ProcessCsvFileUtils.unZip(localFile, localFilePath);
							String cuttomerFile = localFilePath + "/Customer.csv";
							//对下载的文件进行处理  customer
							List<CustomerDto> list = ProcessCsvFileUtils.combinationCustomerList(ProcessCsvFileUtils.analyzeCsv(new File(cuttomerFile),"UTF-8"));
							if(list != null && !list.isEmpty()){
								List<String> customerList = new ArrayList<String>();
								for(int i=0; i<list.size(); i++){
									CustomerDto dto = list.get(i);
									customerList.add(dto.getCustomerID());
								}
								if(customerList != null && !customerList.isEmpty()){
									List<String> customerIdList = new ArrayList<String>();
									int ii = 0;
									for(int i=0; i< customerList.size(); i++){
										ii ++;

										customerIdList.add(customerList.get(i));
										
										if(i % 1000 == 0){
											customerDao.deleteAllExistCustomers(customerIdList);
											customerIdList.clear();
											ii = 0;
										}
									}
									if(ii > 0){
										customerDao.deleteAllExistCustomers(customerIdList);
									}
								}
								customerDao.insertAllCustomers(list);
							}
							//对下载的文件进行处理  vehicleFile
							String vehicleFile = localFilePath + "/Vehicle.csv";
							processVehicleFile(vehicleFile);
							
							//将处理过的压缩包删除
							LOGGER.info("要删除的压缩包名称： -----"+sftpProperties.getPath() + sftpFileDto.getFileName());
							ftpUtil.remove(sftpProperties.getPath() + sftpFileDto.getFileName());
						}catch(Exception e){
							LOGGER.error("processCustomerFileError",e);
						}
					}
					
				}
				ftpUtil.closeChannel();
			}
		} catch (RuntimeException e) {
			LOGGER.info("downLodeCustomerVehicleFile", e);
		} catch (Exception e) {
			LOGGER.info("downLodeCustomerVehicleFile", e);
		}
	}*/

	@Override
	public void processVehicleFile(String localunZipFile) throws AppException {
		try {
			//对下载的文件进行处理
			List<VehicleDto> list = ProcessCsvFileUtils.combinationVehicleList(ProcessCsvFileUtils.analyzeCsv(new File(localunZipFile),"UTF-8"));
			if(list != null && !list.isEmpty()){
				List<String> vehicleList = new ArrayList<String>();
				for(int i=0; i<list.size(); i++){
					VehicleDto dto = list.get(i);
					vehicleList.add(dto.getVehicleID());
				}
				if(vehicleList != null && !vehicleList.isEmpty()){
					List<String> vehicleIdList = new ArrayList<String>();
					int ii = 0;
					for(int i=0; i< vehicleList.size(); i++){
						ii ++;

						vehicleIdList.add(vehicleList.get(i));
						
						if(i % 3000 == 0){
							vehicleDao.deleteAllExistVehicles((vehicleIdList));
							vehicleIdList.clear();
							ii = 0;
						}
					}
					if(ii > 0){
						vehicleDao.deleteAllExistVehicles((vehicleIdList));
					}
				}
				vehicleDao.insertAllVehicles(list);
			}
		}catch(Exception e){
			LOGGER.error("processVehicleError", e);
			throw new AppException("processVehicleError", e);
		}
	}

	/*@Override
	public void processCustomerAndVehicleFile() throws AppException {
		try {
			processCustomerVehicleFile();
		} catch (Exception e) {
			throw new AppException("Exception processCustomerAndVehicleFile", e);
		}
	}*/
    
	public List<SftpFileDto> getAllFileOrderByDateAsc(SftpProperties sftpProperties, String prefix) throws Exception {

        SFTPProcessor ftpUtil = new SFTPProcessor();
        ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);

//        String baseUrl = "/Send";
        String baseUrl = sftpProperties.getPath();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        List vv = ftpUtil.listFiles(baseUrl);
        List<SftpFileDto> fileList  = new ArrayList<SftpFileDto>();
        if(vv!=null){
            for(int ii=0; ii<vv.size(); ii++){

                Object obj=vv.get(ii);
                if(obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry){
                    com.jcraft.jsch.ChannelSftp.LsEntry lsEntry = (com.jcraft.jsch.ChannelSftp.LsEntry) obj;

                    SftpATTRS attrs = lsEntry.getAttrs();

                    String fileName = lsEntry.getFilename();

                    if(!attrs.isDir() && org.apache.commons.lang3.StringUtils.startsWith(fileName, prefix)){
                        SftpFileDto temp = new SftpFileDto(fileName, baseUrl);

                        temp.setDate(dateFormat.parse(fileName.substring(prefix.length(), prefix.length()  + 8)));

                        fileList.add(temp);
                    }
                }

            }
        }

        for (int i = 0; i < fileList.size(); i++) {
            for (int j = i; j < fileList.size(); j++) {
                if(fileList.get(j).getDate().before(fileList.get(i).getDate())){
                    SftpFileDto tempI = fileList.get(i);
                    SftpFileDto tempJ = fileList.get(j);
                    fileList.set(i, tempJ);
                    fileList.set(j, tempI);
                    
                }
            }
        }

       for (SftpFileDto tempFile : fileList) {
            System.out.println(tempFile.getFileName());
        }


        ftpUtil.closeChannel();

        return fileList;
    }

	@Override
	public List<RemindDto> getRemindListByMemberNameOrMoblieOrCarPlateFromMenu(RemindDto dto) throws AppException {

        //每月重置短信初始条数
        CodeInfo codeInfo=codeMapping.getCodeInfoByCode("RemindDefaultQuantity");
        
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(remindQuota!=null){
            remindQuota = remindQuotaDao.findById(remindQuota.getId());
            Date today=new Date();
            Calendar c=Calendar.getInstance();
            c.setTime(today);
            int today_month=c.get(Calendar.MONTH);
            if(remindQuota.getExpireDate()!=null){
                c.setTime(remindQuota.getExpireDate());
            }
            int expire_month=c.get(Calendar.MONTH);
            if(today_month!=expire_month){
                if(codeInfo!=null){
                    remindQuota.setDefaultQuantity(Integer.valueOf(codeInfo.getValue()));
                }else{
                    remindQuota.setDefaultQuantity(0);
                }
                remindQuota.setExpireDate(new Date());
            }
        }else{
            remindQuota=new RemindQuota();
            remindQuota.setDealerId(UserUtil.getCurrentUser().getDealerId());
            remindQuota.setPurchaseQuantity(0);
            if(codeInfo!=null){
                remindQuota.setDefaultQuantity(Integer.valueOf(codeInfo.getValue()));
            }else{
                remindQuota.setDefaultQuantity(0);
            }
            remindQuota.setExpireDate(new Date());
            remindQuotaDao.save(remindQuota);
        }
        /*//取得显示信息
        List<RemindDto> remindDtoList = remindDao.getRemindListByMemberNameOrMoblieOrCarPlate(dto);
        if(remindDtoList != null && !remindDtoList.isEmpty()){
        	for(int i = 0; i < remindDtoList.size(); i++){
        		processServiceRemindForShow(remindDtoList.get(i), UserUtil.getCurrentUser().getDealerId());
        	}
        }
        return remindDtoList;*/
        return null;
    
	}

	@Override
	public void processTenantServiceCenterFile() throws AppException {
		//从SFTP上下载文件
		String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.TENANT_SERVICE_CENTER_JOB);
		SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
		SFTPProcessor ftpUtil = new SFTPProcessor();
        ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
        try {
			if(channelSftp.isConnected()){
				
				List<SftpFileDto> fileList = getAllFileOrderByDateAsc(sftpProperties, "TenantServiceCenter_");
				if(fileList != null && !fileList.isEmpty()){
					//临时目录
					String tmpPath = codeMappingService.getCodeValueByCode("tmpPath", "tmpPath");
//					String remoteFile = "TenantServiceCenter_" + DateFormatUtils.format(new Date(), "yyyyMMdd") + ".txt";
					String remoteFile = fileList.get(fileList.size() - 1).getFileName();
					String remote = "TenantServiceCenter/TenantServiceCenter_";
					String localFilePath = tmpPath + remote + DateFormatUtils.format(new Date(), "yyyyMMdd_HHmmssSSS");
					String localFile = localFilePath + "/" + remoteFile;
					File file = new File(localFilePath);
					if(!file.exists()){
						file.mkdirs();
					}
					ftpUtil.downloadFile(remoteFile, sftpProperties.getPath(), localFile);
					//处理下载文件
					List<Map<String, Object>> dataList = ProcessCsvFileUtils.combinationList(ProcessCsvFileUtils.analyzeCsv(new File(localFile),"GBK"));
					if(dataList != null && !dataList.isEmpty()){
						for(int i=0;i<dataList.size();i++){
							Map<String, Object> raw = dataList.get(i);
							DealerInfoRelMars dealerRelMars = dealerInfoSyncService.getMarsTenantByDearId(Integer.parseInt(raw.get("dealerId").toString()));
							if(dealerRelMars != null){
								//更新
								dealerRelMars.setCompany(raw.get("company").toString());
								dealerRelMars.setDealerId(Integer.parseInt(raw.get("dealerId").toString()));
								dealerRelMars.setMarsDealerId(Integer.parseInt(raw.get("dealerId").toString()));
								dealerRelMars.setMarsTenantId(raw.get("tenantID").toString());
								dealerInfoSyncDao.update(dealerRelMars);
							}else{
								//新增
								DealerInfoRelMars dealerInfoRelMars = new DealerInfoRelMars();
								dealerInfoRelMars.setCompany(raw.get("company").toString());
								dealerInfoRelMars.setDealerId(Integer.parseInt(raw.get("dealerId").toString()));
								dealerInfoRelMars.setMarsDealerId(Integer.parseInt(raw.get("dealerId").toString()));
								dealerInfoRelMars.setMarsTenantId(raw.get("tenantID").toString());
								dealerInfoSyncService.saveDealerInfoSync(dealerInfoRelMars);
							}
						}
					}
					//将处理过的压缩包删除
					LOGGER.info("要删除的压缩包名称： -----"+sftpProperties.getPath() + remoteFile);
					ftpUtil.remove(sftpProperties.getPath() + remoteFile);
				}
			}
		} catch (Exception e) {
			LOGGER.error("processTenantServiceCenterFileError:" + e , e);
		}
	}

	@Override
	public void processCustomerFile(String localunZipFile) throws AppException {
		try {
			//对下载的文件进行处理  customer
			List<CustomerDto> list = ProcessCsvFileUtils.combinationCustomerList(ProcessCsvFileUtils.analyzeCsv(new File(localunZipFile),"UTF-8"));
			if(list != null && !list.isEmpty()){
				List<String> customerList = new ArrayList<String>();
				for(int i=0; i<list.size(); i++){
					CustomerDto dto = list.get(i);
					customerList.add(dto.getCustomerID());
				}
				if(customerList != null && !customerList.isEmpty()){
					List<String> customerIdList = new ArrayList<String>();
					int ii = 0;
					for(int i=0; i< customerList.size(); i++){
						ii ++;

						customerIdList.add(customerList.get(i));
						
						if(i % 3000 == 0){
							customerDao.deleteAllExistCustomers(customerIdList);
							customerIdList.clear();
							ii = 0;
						}
					}
					if(ii > 0){
						customerDao.deleteAllExistCustomers(customerIdList);
					}
				}
				customerDao.insertAllCustomers(list);
			}
		} catch (Exception e) {
			LOGGER.error("processCustomersError", e);
			throw new AppException("processCustomersError", e);
		}
	}

	@Override
	public List<ServiceRemindForMemberDto> getRemindListByMemberNameOrMoblieOrCarPlate(ServiceRemindForMemberDto dto)
			throws AppException {
        //取得显示信息
        List<ServiceRemindForMemberDto> remindDtoList = remindDao.getRemindListByMemberNameOrMoblieOrCarPlate(dto);
        return remindDtoList;
    
	}

	@Override
	public List<HQPromotion> getHQPromotionByIsSelected(ServiceRemindForMemberDto dto) throws AppException {
		return hQPromotionDao.getHQPromotionByIsSelected(dto);
	}

	@Override
	public List<CustomPromotion> getCustomerPromotionByDealerId(Long dealerId,String maintenanceType) throws AppException {
		return customPromotionDao.getCustomerPromotionByDealerId(dealerId,maintenanceType);
	}

	@Override
	public void saveCustomerPromotion(CustomPromotion customerPromotion) throws AppException {
		customPromotionDao.save(customerPromotion);
	}

	@Override
	public Map<String, Object> sendServiceRemindInfoList(boolean resend, boolean appSendFlag, boolean wechatSendFlag,
			boolean msgSendFlag, List<RemindDto> dto, CustomerPromotionDto customerDto) throws AppException {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        rtnMap.put("successMsg", "发送成功！");
        Map<String, String> paraMap = new HashMap<String, String>();
        List<RemindDto> tempDtos=new ArrayList<RemindDto>();
        if(dto==null){
            throw new AppException("sendRemindInfoList", "客户列表为空！");
        }
        for(RemindDto t: dto){
            if(t.getCheckFlag()!=null){
                tempDtos.add(t); 
            }
        }
        
        if(tempDtos.isEmpty()){
            throw new AppException("sendRemindInfoList", "请选择客户后,发送！");
        }
        
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(remindQuota!=null){
            remindQuota=remindQuotaDao.findById(remindQuota.getId());
        }else{
            throw new AppException("reduceRemindQuantityByDealerId","找不到门店的短信包信息！");
        }
        
        if(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity()<tempDtos.size()){
            throw new AppException("reduceRemindQuantityByDealerId","发送"+tempDtos.size()+"条短信,短信包余额为"+(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity())+"条,余额不足,请去充值！");
        }
      
        SmsContentDetailDto smsDto = new SmsContentDetailDto();
        MasterDataDealerInfo dearInfo=maintainDealerDao.getDealerByDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
        Integer sendCount=0;
        //合并短信发送
        List<RemindForSMSDto> mobileAndCarPlateList = new ArrayList<RemindForSMSDto>();
        //取出所有要发的手机号
        for(int i=0; i<tempDtos.size(); i++){
        	String mobilePhone = tempDtos.get(i).getMobliePhone();
        	String carPlate = tempDtos.get(i).getCarPlate();
            RemindForSMSDto remindForSMSDto = new RemindForSMSDto();
        	if(i == 0){
        		remindForSMSDto.setMobliePhone(mobilePhone);
        		remindForSMSDto.setCarPlate(carPlate);
        		mobileAndCarPlateList.add(remindForSMSDto);
        	}else{
        		boolean isExists = false;
        		for(int j=0; j<mobileAndCarPlateList.size(); j++){
        			String mobilePhoneJ = mobileAndCarPlateList.get(j).getMobliePhone();
        			String carPlateJ = mobileAndCarPlateList.get(j).getCarPlate();
        			if(Utils.getString(mobilePhone).equals(Utils.getString(mobilePhoneJ))
        					&& Utils.getString(carPlate).equals(Utils.getString(carPlateJ))){
        				isExists = true;
        			}
        		}
        		if(!isExists){
        			remindForSMSDto.setMobliePhone(mobilePhone);
            		remindForSMSDto.setCarPlate(carPlate);
            		mobileAndCarPlateList.add(remindForSMSDto);
        		}
        	}
        }
        //根据手机号将要发的信息进行整合
        List<RemindDto> preRemindDtos = new ArrayList<RemindDto>();
        if(mobileAndCarPlateList != null && !mobileAndCarPlateList.isEmpty()){
        	for(RemindForSMSDto remindForSMSDto:mobileAndCarPlateList){
        		RemindDto remindDtoForInsert = new RemindDto();
        		String carplateString = "";
        		String maintenanceItem = "";
        		String lastPartBrand = "";
        		for(int i=0; i<tempDtos.size(); i++){
        			RemindDto remindDto = tempDtos.get(i);
        			if(remindForSMSDto.getMobliePhone().equals(remindDto.getMobliePhone())
        					&& remindForSMSDto.getCarPlate().equals(remindDto.getCarPlate())){
        				String memberName = remindDto.getMemberName();
        				
        				if(!(carplateString.equals(remindDto.getCarPlate() + " "))){
        					carplateString += remindDto.getCarPlate() + " ";
        				}
        				
        				String nextCalcDate = remindDto.getNextCalcDate().substring(0, 7);
        				
        				if(!(maintenanceItem.equals(remindDto.getMaintenanceItem() + " "))){
        					maintenanceItem += remindDto.getMaintenanceItem() + " ";
        				}
        				
        				if(!(lastPartBrand.equals(remindDto.getLastPartBrand() + " "))){
        					lastPartBrand += remindDto.getLastPartBrand() + " ";
        				}
        				
        				remindDtoForInsert.setMemberName(memberName);
        				remindDtoForInsert.setMobliePhone(remindForSMSDto.getMobliePhone());
        				remindDtoForInsert.setCarPlate(carplateString);
        				remindDtoForInsert.setNextCalcDate(nextCalcDate);
        				remindDtoForInsert.setMaintenanceItem(maintenanceItem);
        				remindDtoForInsert.setLastPartBrand(lastPartBrand);
        			}
        		}
        		preRemindDtos.add(remindDtoForInsert);
        	}
        }
        //对处理好的列表发短信
        if(!preRemindDtos.isEmpty()){
        	for(RemindDto remindDto : preRemindDtos){
                paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
                paraMap.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
                paraMap.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
                paraMap.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate());
                paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
                paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
                if("-1".equals(customerDto.getSalesPromotion())){
                	paraMap.put(SmsTemplateVariable.VARIABLE_PROMOTION, "无");
                }else{
                	paraMap.put(SmsTemplateVariable.VARIABLE_PROMOTION, customerDto.getSalesPromotion());
                }
                if(dearInfo!=null){
                    paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                    paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                }
                smsDto.setTemplateNo(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
               try{
                   smsDto.setDestMobile(Long.valueOf(remindDto.getMobliePhone()));
               }catch(Exception e){
                   rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                   continue;
               }
                smsDto.setParaMap(paraMap);
                try{
                    smContentService.createSmsContent(smsDto);
                }catch(Exception e){
                }
        	}
        }
        //处理history
        for (RemindDto remindDto : tempDtos) {
        	Map<String, String> paraMapForHistory = new HashMap<String, String>();
        	paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate().substring(0, 10));
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
            paraMapForHistory.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
            if("-1".equals(customerDto.getSalesPromotion())){
            	paraMapForHistory.put(SmsTemplateVariable.VARIABLE_PROMOTION, "无");
            }else{
            	paraMapForHistory.put(SmsTemplateVariable.VARIABLE_PROMOTION, customerDto.getSalesPromotion());
            }
            if(dearInfo!=null){
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
            }
            sendCount++;
            ServiceRemindHistory srh=new ServiceRemindHistory();
            srh.setDealerId(UserUtil.getCurrentUser().getDealerId());
            List<SmsTemplate> smsTemplates = msgTemplateDao.findTemplateByTemplateCode(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
            String msgContent="";
            if(smsTemplates!=null){
                msgContent=smContentService.generateSmsContent(smsTemplates.get(0),paraMapForHistory);
            }
            srh.setServiceRemindId(remindDto.getId());
            srh.setMessageContent(msgContent);
            srh.setStatus(1);
            serviceRemindHistoryDao.save(srh);
        }
        try{
            reduceRemindQuantityByDealerId(UserUtil.getCurrentUser().getDealerId(),sendCount);
        }catch(AppException e){
            LOGGER.error("门店："+UserUtil.getCurrentUser().getDealerId()+"发送短信减少短信数量出错,实际发送短信数量为"+sendCount, e);
            throw new AppException("sendAllRemindInfo", "发送成功,减少短信数量失败,请联系系统管理员！");
        }
        return rtnMap;
    }

	@Override
	public Map<String, Object> sendAllRemindInfo(boolean resend, boolean appSendFlag, boolean wechatSendFlag,
			boolean msgSendFlag, ServiceRemindForMemberDto serviceRemindForMemberDto, CustomerPromotionDto customerDto) throws AppException {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        rtnMap.put("successMsg", "发送成功！");
        Map<String, String> paraMap = new HashMap<String, String>();
        if(serviceRemindForMemberDto==null){
            throw new AppException("sendRemindInfoList", "客户列表为空！");
        }
        List<ServiceRemindForMemberDto> remindDtos = remindDao.getRemindListByMemberNameOrMoblieOrCarPlateNoPage(serviceRemindForMemberDto);
        List<ServiceRemindForMemberDto> tempDtos=new ArrayList<ServiceRemindForMemberDto>();
        for(ServiceRemindForMemberDto t: remindDtos){
                tempDtos.add(t); 
        }
        
        if(tempDtos.isEmpty()){
            throw new AppException("sendRemindInfoList", "请选择客户后,发送！");
        }
        
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(remindQuota!=null){
            remindQuota=remindQuotaDao.findById(remindQuota.getId());
        }else{
            throw new AppException("reduceRemindQuantityByDealerId","找不到门店的短信包信息！");
        }
        
        if(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity()<tempDtos.size()){
            throw new AppException("reduceRemindQuantityByDealerId","发送"+tempDtos.size()+"条短信,短信包余额为"+(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity())+"条,余额不足,请去充值！");
        }
      
        
            SmsContentDetailDto smsDto = new SmsContentDetailDto();
            MasterDataDealerInfo dearInfo=maintainDealerDao.getDealerByDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
            Integer sendCount=0;
          //合并短信发送
            List<RemindForSMSDto> mobileAndCarPlateList = new ArrayList<RemindForSMSDto>();
            //取出所有要发的手机号
            for(int i=0; i<tempDtos.size(); i++){
            	String mobilePhone = tempDtos.get(i).getMobliePhone();
            	String carPlate = tempDtos.get(i).getCarPlate();
                RemindForSMSDto remindForSMSDto = new RemindForSMSDto();
            	if(i == 0){
            		remindForSMSDto.setMobliePhone(mobilePhone);
            		remindForSMSDto.setCarPlate(carPlate);
            		mobileAndCarPlateList.add(remindForSMSDto);
            	}else{
            		boolean isExists = false;
            		for(int j=0; j<mobileAndCarPlateList.size(); j++){
            			String mobilePhoneJ = mobileAndCarPlateList.get(j).getMobliePhone();
            			String carPlateJ = mobileAndCarPlateList.get(j).getCarPlate();
            			if(Utils.getString(mobilePhone).equals(Utils.getString(mobilePhoneJ))
            					&& Utils.getString(carPlate).equals(Utils.getString(carPlateJ))){
            				isExists = true;
            			}
            		}
            		if(!isExists){
            			remindForSMSDto.setMobliePhone(mobilePhone);
                		remindForSMSDto.setCarPlate(carPlate);
                		mobileAndCarPlateList.add(remindForSMSDto);
            		}
            	}
            }
            //根据手机号将要发的信息进行整合
            List<RemindDto> preRemindDtos = new ArrayList<RemindDto>();
            if(mobileAndCarPlateList != null && !mobileAndCarPlateList.isEmpty()){
            	for(RemindForSMSDto remindForSMSDto:mobileAndCarPlateList){
            		RemindDto remindDtoForInsert = new RemindDto();
            		String carplateString = "";
            		String maintenanceItem = "";
            		String lastPartBrand = "";
            		for(int i=0; i<tempDtos.size(); i++){
            			ServiceRemindForMemberDto remindDto = tempDtos.get(i);
            			if(remindForSMSDto.getMobliePhone().equals(remindDto.getMobliePhone())
            					&& remindForSMSDto.getCarPlate().equals(remindDto.getCarPlate())){
            				String memberName = remindDto.getMemberName();
            				
            				if(!(carplateString.equals(remindDto.getCarPlate() + " "))){
            					carplateString += remindDto.getCarPlate() + " ";
            				}
            				
            				String nextCalcDate = remindDto.getNextCalcDate().substring(0, 7);
            				
            				if(!(maintenanceItem.equals(remindDto.getMaintenanceItem() + " "))){
            					maintenanceItem += remindDto.getMaintenanceItem() + " ";
            				}
            				
            				if(!(lastPartBrand.equals(remindDto.getLastPartBrand() + " "))){
            					lastPartBrand += remindDto.getLastPartBrand() + " ";
            				}
            				
            				remindDtoForInsert.setMemberName(memberName);
            				remindDtoForInsert.setMobliePhone(remindForSMSDto.getMobliePhone());
            				remindDtoForInsert.setCarPlate(carplateString);
            				remindDtoForInsert.setNextCalcDate(nextCalcDate);
            				remindDtoForInsert.setMaintenanceItem(maintenanceItem);
            				remindDtoForInsert.setLastPartBrand(lastPartBrand);
            			}
            		}
            		preRemindDtos.add(remindDtoForInsert);
            	}
            }
            //对处理好的列表发短信
            if(!preRemindDtos.isEmpty()){
            	for(RemindDto remindDto : preRemindDtos){
                    paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
                    paraMap.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
                    paraMap.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
                    paraMap.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate());
                    paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
                    paraMap.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
                    if("-1".equals(customerDto.getSalesPromotion())){
                    	paraMap.put(SmsTemplateVariable.VARIABLE_PROMOTION, "无");
                    }else{
                    	paraMap.put(SmsTemplateVariable.VARIABLE_PROMOTION, customerDto.getSalesPromotion());
                    }
                    if(dearInfo!=null){
                        paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                        paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                    }
                    smsDto.setTemplateNo(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
                    
                   try{
                       smsDto.setDestMobile(Long.valueOf(remindDto.getMobliePhone()));
                   }catch(Exception e){
                       rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                       continue;
                   }
                    smsDto.setParaMap(paraMap);
                    try{
                        smContentService.createSmsContent(smsDto);
                    }catch(Exception e){
                    }
            	}
            }
            //处理history
            for (ServiceRemindForMemberDto remindDto : tempDtos) {
            	Map<String, String> paraMapForHistory = new HashMap<String, String>();
            	paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, remindDto.getMemberName());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MOBLIE_PHONE, remindDto.getMobliePhone());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NAME, remindDto.getCarPlate());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_MANTENANCE_DATE, remindDto.getNextCalcDate().substring(0, 10));
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_SERVICE_TYPE, remindDto.getMaintenanceItem());
                paraMapForHistory.put(SmsTemplateVariable.VARIABLE_SERVICE_ITEM, remindDto.getLastPartBrand());
                if("-1".equals(customerDto.getSalesPromotion())){
                	paraMapForHistory.put(SmsTemplateVariable.VARIABLE_PROMOTION, "无");
                }else{
                	paraMapForHistory.put(SmsTemplateVariable.VARIABLE_PROMOTION, customerDto.getSalesPromotion());
                }
                if(dearInfo!=null){
                    paraMapForHistory.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                    paraMapForHistory.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                }
                sendCount++;
                ServiceRemindHistory srh=new ServiceRemindHistory();
                srh.setDealerId(UserUtil.getCurrentUser().getDealerId());
                List<SmsTemplate> smsTemplates = msgTemplateDao.findTemplateByTemplateCode(SmsTemplateNoConstants.SEND_REMIND_MSG_TEMPLATE_NO);
                String msgContent="";
                if(smsTemplates!=null){
                    msgContent=smContentService.generateSmsContent(smsTemplates.get(0),paraMapForHistory);
                }
                srh.setServiceRemindId(remindDto.getId());
                srh.setMessageContent(msgContent);
                srh.setStatus(1);
                serviceRemindHistoryDao.save(srh);
            }
            try{
                reduceRemindQuantityByDealerId(UserUtil.getCurrentUser().getDealerId(),sendCount);
            }catch(AppException e){
                LOGGER.error("门店："+UserUtil.getCurrentUser().getDealerId()+"发送短信减少短信数量出错,实际发送短信数量为"+sendCount, e);
                throw new AppException("sendAllRemindInfo", "发送成功,减少短信数量失败,请联系系统管理员！");
            }
            
            return rtnMap;
       
    }

	@Override
	public List<ServiceRemind> getAllServiceRemind() throws AppException {
		return serviceRemindDao.getAllServiceRemind();
	}

	@Override
	public List<ServiceRemindHistoryDto> getServiceRemindHistoryByMobilePhone(ServiceRemindForMemberDto dto) throws AppException {
		return remindDao.getServiceRemindHistoryByMobilePhone(dto);
	}

	@Override
	public List<CustomerGroup> getTrCustomerGroupByDealerId(Long dealerId) throws AppException {
		return customerGroupDao.getCustomerGroupByDealerId(dealerId);
	}

	@Override
	public List<ServiceRemindForMemberDto> getRemindListForCreateCustomerGroup(ServiceRemindForMemberDto dto)
			throws AppException {
		//取得显示信息
        List<ServiceRemindForMemberDto> remindDtoList = remindDao.getRemindListForCreateCustomerGroup(dto);
        return remindDtoList;
	}

	@Override
	public boolean saveCustomerGroup(ServiceRemindSubmitDto srDto, ServiceRemindForMemberDto dto,Long dealerId) throws AppException {
		if(srDto == null){
			throw new AppException("saveCustomerGroup", "客户列表为空！");
		}else{
			List<ServiceRemindForMemberDto> list = srDto.getRemindList();
			if(list != null && !list.isEmpty()){
				List<ServiceRemindForMemberDto> checkedList = new ArrayList<ServiceRemindForMemberDto>();
				for(ServiceRemindForMemberDto srMemberDto : list){
					if(srMemberDto.getCheckFlag() != null){
						checkedList.add(srMemberDto);
					}
				}
				if(checkedList != null && !checkedList.isEmpty()){
					try {
						for(ServiceRemindForMemberDto srForMemberdto : checkedList){
							List<CustomerGroup> cusGroups = customerGroupDao.getCustomerGroupByDealerIdAndGroupName(dealerId, dto.getGroupName());
							if(cusGroups == null || cusGroups.isEmpty()){
								CustomerGroup customerGroup = new CustomerGroup();
								customerGroup.setDealer_id(dealerId);
								customerGroup.setGroup_name(dto.getGroupName());
								customerGroupDao.save(customerGroup);
							}
							
							List<CustomerGroup> customerGroups = customerGroupDao.getCustomerGroupByDealerIdAndGroupName(dealerId, dto.getGroupName());
							if(customerGroups != null && !customerGroups.isEmpty()){
								List<TrCustomerGroup> groupList = trCustomerGroupDao.getTrCustomerGroup(dealerId, customerGroups.get(0).getId(), Long.parseLong(srForMemberdto.getMemberId()));
								if(groupList == null || groupList.isEmpty()){
									TrCustomerGroup trCustomerGroup = new TrCustomerGroup();
									trCustomerGroup.setDealer_id(dealerId);
									if(org.apache.commons.lang.StringUtils.isNotBlank(srForMemberdto.getMemberId())){
										trCustomerGroup.setCustomer_id(Long.parseLong(srForMemberdto.getMemberId()));
									}else{
										trCustomerGroup.setCustomer_id(null);
									}
									trCustomerGroup.setGroup_id(customerGroups.get(0).getId());
									
									trCustomerGroupDao.save(trCustomerGroup);
								}
							}
						}
						return true;
					} catch (Exception e) {
						LOGGER.error("saveCustomerGroup "+e);
					}
				}else{
					throw new AppException("saveCustomerGroup", "请选择用户！");
				}
			}else{
				throw new AppException("saveCustomerGroup", "客户列表为空！");
			}
		}
		return false;
	}

	@Override
	public Map<String, Object> sendAllRemindInfoForNotice(boolean resend, boolean appSendFlag, boolean wechatSendFlag,
			boolean msgSendFlag, ServiceRemindForMemberDto serviceRemindForMemberDto, CustomerPromotionDto customerDto)
			throws AppException {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        rtnMap.put("successMsg", "发送成功！");
        Map<String, String> paraMap = new HashMap<String, String>();
        if(serviceRemindForMemberDto==null){
            throw new AppException("sendRemindInfoList", "客户列表为空！");
        }
        List<ServiceRemindForMemberDto> remindDtos = remindDao.getRemindListByMemberNameOrMoblieOrCarPlateNoPage(serviceRemindForMemberDto);
        List<ServiceRemindForMemberDto> tempDtos=new ArrayList<ServiceRemindForMemberDto>();
        for(ServiceRemindForMemberDto t: remindDtos){
                tempDtos.add(t); 
        }
        
        if(tempDtos.isEmpty()){
            throw new AppException("sendRemindInfoList", "请选择客户后,发送！");
        }
        
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(remindQuota!=null){
            remindQuota=remindQuotaDao.findById(remindQuota.getId());
        }else{
            throw new AppException("reduceRemindQuantityByDealerId","找不到门店的短信包信息！");
        }
        
        if(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity()<tempDtos.size()){
            throw new AppException("reduceRemindQuantityByDealerId","发送"+tempDtos.size()+"条短信,短信包余额为"+(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity())+"条,余额不足,请去充值！");
        }
      
        
            SmsContentDetailDto smsDto = new SmsContentDetailDto();
            MasterDataDealerInfo dearInfo=maintainDealerDao.getDealerByDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
            Integer sendCount=0;
          //合并短信发送
            List<RemindForSMSDto> mobileAndCarPlateList = new ArrayList<RemindForSMSDto>();
            //取出所有要发的手机号
            for(int i=0; i<tempDtos.size(); i++){
            	String mobilePhone = tempDtos.get(i).getMobliePhone();
            	String carPlate = tempDtos.get(i).getCarPlate();
                RemindForSMSDto remindForSMSDto = new RemindForSMSDto();
            	if(i == 0){
            		remindForSMSDto.setMobliePhone(mobilePhone);
            		remindForSMSDto.setCarPlate(carPlate);
            		mobileAndCarPlateList.add(remindForSMSDto);
            	}else{
            		boolean isExists = false;
            		for(int j=0; j<mobileAndCarPlateList.size(); j++){
            			String mobilePhoneJ = mobileAndCarPlateList.get(j).getMobliePhone();
            			String carPlateJ = mobileAndCarPlateList.get(j).getCarPlate();
            			if(Utils.getString(mobilePhone).equals(Utils.getString(mobilePhoneJ))
            					&& Utils.getString(carPlate).equals(Utils.getString(carPlateJ))){
            				isExists = true;
            			}
            		}
            		if(!isExists){
            			remindForSMSDto.setMobliePhone(mobilePhone);
                		remindForSMSDto.setCarPlate(carPlate);
                		mobileAndCarPlateList.add(remindForSMSDto);
            		}
            	}
            }
            //根据手机号将要发的信息进行整合
            List<RemindDto> preRemindDtos = new ArrayList<RemindDto>();
            if(mobileAndCarPlateList != null && !mobileAndCarPlateList.isEmpty()){
            	for(RemindForSMSDto remindForSMSDto:mobileAndCarPlateList){
            		RemindDto remindDtoForInsert = new RemindDto();
            		String carplateString = "";
            		String maintenanceItem = "";
            		String lastPartBrand = "";
            		for(int i=0; i<tempDtos.size(); i++){
            			ServiceRemindForMemberDto remindDto = tempDtos.get(i);
            			if(remindForSMSDto.getMobliePhone().equals(remindDto.getMobliePhone())
            					&& remindForSMSDto.getCarPlate().equals(remindDto.getCarPlate())){
            				String memberName = remindDto.getMemberName();
            				
            				if(!(carplateString.equals(remindDto.getCarPlate() + " "))){
            					carplateString += remindDto.getCarPlate() + " ";
            				}
            				
            				String nextCalcDate = remindDto.getNextCalcDate().substring(0, 7);
            				
            				if(!(maintenanceItem.equals(remindDto.getMaintenanceItem() + " "))){
            					maintenanceItem += remindDto.getMaintenanceItem() + " ";
            				}
            				
            				if(!(lastPartBrand.equals(remindDto.getLastPartBrand() + " "))){
            					lastPartBrand += remindDto.getLastPartBrand() + " ";
            				}
            				
            				remindDtoForInsert.setMemberName(memberName);
            				remindDtoForInsert.setMobliePhone(remindForSMSDto.getMobliePhone());
            				remindDtoForInsert.setCarPlate(carplateString);
            				remindDtoForInsert.setNextCalcDate(nextCalcDate);
            				remindDtoForInsert.setMaintenanceItem(maintenanceItem);
            				remindDtoForInsert.setLastPartBrand(lastPartBrand);
            			}
            		}
            		preRemindDtos.add(remindDtoForInsert);
            	}
            }
            //对处理好的列表发短信
            if(!preRemindDtos.isEmpty()){
            	for(RemindDto remindDto : preRemindDtos){
                    if("".equals(customerDto.getPromotionalContent())){
                    	paraMap.put(SmsTemplateVariable.VARIABLE_ANNOUNCEMENT, "{announcement}");
                    }else{
                    	paraMap.put(SmsTemplateVariable.VARIABLE_ANNOUNCEMENT, customerDto.getPromotionalContent());
                    }
                    if(dearInfo!=null){
                        paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                        paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                    }
                    smsDto.setTemplateNo(SmsTemplateNoConstants.DEALER_ANNOUNCEMENT);
                    
                   try{
                       smsDto.setDestMobile(Long.valueOf(remindDto.getMobliePhone()));
                   }catch(Exception e){
                       rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                       continue;
                   }
                    smsDto.setParaMap(paraMap);
                    try{
                        smContentService.createSmsContent(smsDto);
                    }catch(Exception e){
                    }
            	}
            }
            try{
                reduceRemindQuantityByDealerId(UserUtil.getCurrentUser().getDealerId(),sendCount);
            }catch(AppException e){
                LOGGER.error("门店："+UserUtil.getCurrentUser().getDealerId()+"发送短信减少短信数量出错,实际发送短信数量为"+sendCount, e);
                throw new AppException("sendAllRemindInfo", "发送成功,减少短信数量失败,请联系系统管理员！");
            }
            
            return rtnMap;
       
    }

	@Override
	public Map<String, Object> sendServiceRemindInfoListForNotice(boolean resend, boolean appSendFlag,
			boolean wechatSendFlag, boolean msgSendFlag, List<RemindDto> dto, CustomerPromotionDto customerDto)
			throws AppException {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        rtnMap.put("successMsg", "发送成功！");
        Map<String, String> paraMap = new HashMap<String, String>();
        List<RemindDto> tempDtos=new ArrayList<RemindDto>();
        if(dto==null){
            throw new AppException("sendRemindInfoList", "客户列表为空！");
        }
        for(RemindDto t: dto){
            if(t.getCheckFlag()!=null){
                tempDtos.add(t); 
            }
        }
        
        if(tempDtos.isEmpty()){
            throw new AppException("sendRemindInfoList", "请选择客户后,发送！");
        }
        
        RemindQuota remindQuota =remindQuotaDao.getRemindQuotaByDealerId(UserUtil.getCurrentUser().getDealerId());
        if(remindQuota!=null){
            remindQuota=remindQuotaDao.findById(remindQuota.getId());
        }else{
            throw new AppException("reduceRemindQuantityByDealerId","找不到门店的短信包信息！");
        }
        
        if(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity()<tempDtos.size()){
            throw new AppException("reduceRemindQuantityByDealerId","发送"+tempDtos.size()+"条短信,短信包余额为"+(remindQuota.getDefaultQuantity()+remindQuota.getPurchaseQuantity())+"条,余额不足,请去充值！");
        }
      
        SmsContentDetailDto smsDto = new SmsContentDetailDto();
        MasterDataDealerInfo dearInfo=maintainDealerDao.getDealerByDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
        Integer sendCount=0;
        //合并短信发送
        List<RemindForSMSDto> mobileAndCarPlateList = new ArrayList<RemindForSMSDto>();
        //取出所有要发的手机号
        for(int i=0; i<tempDtos.size(); i++){
        	String mobilePhone = tempDtos.get(i).getMobliePhone();
        	String carPlate = tempDtos.get(i).getCarPlate();
            RemindForSMSDto remindForSMSDto = new RemindForSMSDto();
        	if(i == 0){
        		remindForSMSDto.setMobliePhone(mobilePhone);
        		remindForSMSDto.setCarPlate(carPlate);
        		mobileAndCarPlateList.add(remindForSMSDto);
        	}else{
        		boolean isExists = false;
        		for(int j=0; j<mobileAndCarPlateList.size(); j++){
        			String mobilePhoneJ = mobileAndCarPlateList.get(j).getMobliePhone();
        			String carPlateJ = mobileAndCarPlateList.get(j).getCarPlate();
        			if(Utils.getString(mobilePhone).equals(Utils.getString(mobilePhoneJ))
        					&& Utils.getString(carPlate).equals(Utils.getString(carPlateJ))){
        				isExists = true;
        			}
        		}
        		if(!isExists){
        			remindForSMSDto.setMobliePhone(mobilePhone);
            		remindForSMSDto.setCarPlate(carPlate);
            		mobileAndCarPlateList.add(remindForSMSDto);
        		}
        	}
        }
        //根据手机号将要发的信息进行整合
        List<RemindDto> preRemindDtos = new ArrayList<RemindDto>();
        if(mobileAndCarPlateList != null && !mobileAndCarPlateList.isEmpty()){
        	for(RemindForSMSDto remindForSMSDto:mobileAndCarPlateList){
        		RemindDto remindDtoForInsert = new RemindDto();
        		String carplateString = "";
        		String maintenanceItem = "";
        		String lastPartBrand = "";
        		for(int i=0; i<tempDtos.size(); i++){
        			RemindDto remindDto = tempDtos.get(i);
        			if(remindForSMSDto.getMobliePhone().equals(remindDto.getMobliePhone())
        					&& remindForSMSDto.getCarPlate().equals(remindDto.getCarPlate())){
        				String memberName = remindDto.getMemberName();
        				
        				if(!(carplateString.equals(remindDto.getCarPlate() + " "))){
        					carplateString += remindDto.getCarPlate() + " ";
        				}
        				
        				String nextCalcDate = remindDto.getNextCalcDate().substring(0, 7);
        				
        				if(!(maintenanceItem.equals(remindDto.getMaintenanceItem() + " "))){
        					maintenanceItem += remindDto.getMaintenanceItem() + " ";
        				}
        				
        				if(!(lastPartBrand.equals(remindDto.getLastPartBrand() + " "))){
        					lastPartBrand += remindDto.getLastPartBrand() + " ";
        				}
        				
        				remindDtoForInsert.setMemberName(memberName);
        				remindDtoForInsert.setMobliePhone(remindForSMSDto.getMobliePhone());
        				remindDtoForInsert.setCarPlate(carplateString);
        				remindDtoForInsert.setNextCalcDate(nextCalcDate);
        				remindDtoForInsert.setMaintenanceItem(maintenanceItem);
        				remindDtoForInsert.setLastPartBrand(lastPartBrand);
        			}
        		}
        		preRemindDtos.add(remindDtoForInsert);
        	}
        }
        //对处理好的列表发短信
        if(!preRemindDtos.isEmpty()){
        	for(RemindDto remindDto : preRemindDtos){
                if("".equals(customerDto.getPromotionalContent())){
                	paraMap.put(SmsTemplateVariable.VARIABLE_ANNOUNCEMENT, "{announcement}");
                }else{
                	paraMap.put(SmsTemplateVariable.VARIABLE_ANNOUNCEMENT, customerDto.getPromotionalContent());
                }
                if(dearInfo!=null){
                    paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_ADDRESS, dearInfo.getAddress());
                    paraMap.put(SmsTemplateVariable.VARIABLE_DEARLER_PHONE_NUM, dearInfo.getTelephone());
                }
                smsDto.setTemplateNo(SmsTemplateNoConstants.DEALER_ANNOUNCEMENT);
                
               try{
                   smsDto.setDestMobile(Long.valueOf(remindDto.getMobliePhone()));
               }catch(Exception e){
                   rtnMap.put("successMsg", "发送成功(存在发送失败客户)！");
                   continue;
               }
                smsDto.setParaMap(paraMap);
                try{
                    smContentService.createSmsContent(smsDto);
                }catch(Exception e){
                }
        	}
        }
        try{
            reduceRemindQuantityByDealerId(UserUtil.getCurrentUser().getDealerId(),sendCount);
        }catch(AppException e){
            LOGGER.error("门店："+UserUtil.getCurrentUser().getDealerId()+"发送短信减少短信数量出错,实际发送短信数量为"+sendCount, e);
            throw new AppException("sendAllRemindInfo", "发送成功,减少短信数量失败,请联系系统管理员！");
        }
        return rtnMap;
    }

	@Override
	public List<ServiceRemindForMemberDto> getRemindListForNotice(ServiceRemindForMemberDto dto) throws AppException {
		//取得显示信息
        List<ServiceRemindForMemberDto> remindDtoList = remindDao.getRemindListForNotice(dto);
        return remindDtoList;
	}

	@Override
	public List<CustomPromotion> getCustomerPromotionByPromotion(Long dealerId, String promotion) throws AppException {
		return customPromotionDao.getCustomerPromotionByPromotion(dealerId, promotion);
	}

	@Override
	public MasterDataDealerInfo getDealerByDealerNum(String dealerNum) throws AppException {
		return maintainDealerDao.getDealerByDealerNum(dealerNum);
	}
	
 /*   *//**
     * 解析数据
     * @param result
     * @return
     * @throws Exception 
     *//*
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<Map<String, Object>> getFileInfo(String result, 
                                           String synchronizationMethod) throws AppException{
        JSONObject jsonObject = JSONObject.parseObject(result);
        Map<String, Object> dataMap = null;
        Map<String, Object> fileNameMap = null;
        List<Map<String, Object>> resultList = new ArrayList();
            String dataString = jsonObject.getString("data");
            JSONArray jsonArray = JSONArray.parseArray(dataString);
            String currentDte = DateUtil.getDateText(new Date());
            //本地存储目录
            String localFilePath = "/crmFile/remindFile/remindService.csv";
                List<String> list = MasterInfoUtils.analyzeCsv(new File(localFilePath));
                List<Map<String, Object>> dataList = MasterInfoUtils.combinationCommaList(list);
        return null;
    }*/
}
